package maconel.app.hlreader;

import android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;

public class TextView extends SurfaceView implements SurfaceHolder.Callback {
    Control[] mControls;
    ContentControl mContentControl = new ContentControl();

    public TextView(Context context) {
        super(context);
    }

    public TextView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public void init() {
        getHolder().addCallback(this);
        this.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() != MotionEvent.ACTION_UP) {
                    return true;
                }

                Control[] controls = ((TextView) v).mControls;
                SurfaceHolder holder = getHolder();
                Canvas canvas = holder.lockCanvas();
                for (int i = 0; i < controls.length; i++) {
                    if (controls[i].inRect((int) event.getX(), (int) event.getY())) {
                        controls[i].onClick(canvas, (int) event.getX(), (int) event.getY());
                        break;
                    }
                }
                holder.unlockCanvasAndPost(canvas);
                return true;
            }
        });

        mControls = new Control[1];
        mControls[0] = mContentControl;

        for (int i = 0; i < mControls.length; i++) {
            mControls[0].init();
        }
    }

    public void uninit() {
        for (int i = 0; i < mControls.length; i++) {
            mControls[0].uninit();
        }
    }

    public void drawFirst() {
        SurfaceHolder holder = getHolder();
        Canvas canvas = holder.lockCanvas();
        for (int i = 0; i < mControls.length; i++) {
            mControls[0].draw(canvas);
        }
        holder.unlockCanvasAndPost(canvas);
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
        mContentControl.setRect(getTop(), getLeft(), getWidth(), getHeight());

        drawFirst();
    }
}
